var global_jw_var = new Array; 
var keyStr = "ABCDEFGHIJKLMNOP" +
		   "QRSTUVWXYZabcdef" +
		   "ghijklmnopqrstuv" +
		   "wxyz0123456789+/" +
		   "=";
var jingle_tag = "http://www.useetv.com/video_ads.xml";
var is_ios = false;
var ua	= navigator.userAgent.toLowerCase();
if(ua.search('iphone')!= -1 || ua.search('ipad') != -1 ) is_ios = true;
 function _get_file(input) {
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;
     input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

     do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
           output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
           output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

     } while (i < input.length);

     return unescape(output);
  }		   
function crdecode(url) {
  return decodeURIComponent(url.replace(/\+/g, ' '));
}  
var jw_register = function(player, config, div) {
	var is_valid = false;
	var ugaq = config.gaq;
	var is_complete = false;
	var news_ticker_data ='';
	var ticker_show_once = false;
    function setup(evt) {
		resize();
        div.className = "alert alert-block";
		div.style.display = 'none'; 
		div.style.padding = '15px 10px'; 
		div.style.textAlign = 'center'; 
		//if ($.browser.webkit) div.style.backgroundColor = "#fff";
		if(global_jw_var['load_ads1'] && !global_jw_var['load_ads2']){
			global_jw_var['load_ads2'] = true;
			player.playAd(jingle_tag); 
		}
		//console.log(config);
		if(config.news_ticker){
				$('head').append('<script src="http://assets.useetv.com/js/jquery.li-scroller.1.0.js?v=2" type="text/javascript" ></script>');
				$('head').append('<link href="http://assets.useetv.com/css/li-scroller.css" rel="stylesheet" type="text/css" />');
				global_jw_var['load_ticker'] = $.ajax({
				url: config.news_ticker,
				type : 'get',
				cache : false,
				dataType :'json',
				success: function(data) {
						if(!data) return;
						if(data.length == 0) return;
						var nt_parent = document.createElement('div');
						nt_parent.style.cssText = "position:absolute;bottom:10px;height:25px;line-height:25px;backgorund-color:#fff;opacity:0.8;z-index:100;width:"+ player.getWidth() +"px;";
						var ul = '<ul id="ticker01">';
							for(ix in data){
								ul += '<li>'+data[ix]+'</li>';
							}
						ul += '</ul>';
						nt_parent.innerHTML = ul;
						news_ticker_data = nt_parent;

				}});
		}
		if(config.validate && !is_valid){
			var alert_msg = '<fieldset>'+
										'<div>Silahkan login terlebih dahulu</div>'+
										'<a href="'+config.back_url+'" class="btn btn-inverse" style="margin-top:20px;"> OK </a></fieldset>';
			if(config.token){
				var sdata = {token:config.token};
				if(global_jw_var['getUserByToken']) global_jw_var['getUserByToken'].abort();
				var urls = _root_url+'services/getUserByToken';
				global_jw_var['getUserByToken'] = $.ajax({
					url: urls,
					data: sdata,
					type : 'post',
					dataType :'json',
					success: function(data) {
						if(data.result){
							is_valid = true
							if(player.getState()!="PLAYING") player.play();
						}
						else{
							div.style.display = '';
							div.innerHTML = alert_msg;
						}
					}
				});
			}else{
				div.style.display = '';
				div.innerHTML = alert_msg;			
			}
		}else{ 
			is_valid = true;
		}
		ugaq.push(['stats._setAccount', GA_STATS_ACCOUNT]);
         
    };
	
	function playit(){
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;
		if(!is_valid) player.stop();
		if(!vd_name) vd_name = config.vd_name;
		if(news_ticker_data && !ticker_show_once){
			var tic_to = setTimeout(function(){
				$(div).parent().append(news_ticker_data);
				var ss = $("ul#ticker01").liScroll();
				ticker_show_once = true;
				var t_tic_to = setTimeout(function(){$(news_ticker_data).remove();},60000);
			},5000);
		}
		 //ugaq.push(['stats._trackEvent', 'Video', 'Playing - '+vd_name, config.vd_name]);
		 ugaq.push(['stats._trackEvent', config.vd_category+' Play', items_meta.file, window.location.href]);
	}
	
	function pauseit()
	{
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;
		if(!vd_name) vd_name = config.vd_name;			
		//ugaq.push(['stats._trackEvent', 'Video', 'Pause - '+vd_name, config.vd_name]);
	}
	
	function completeit()
	{
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;
		
		//ugaq.push(['stats._trackEvent', 'Video', 'Complete - '+vd_name, config.vd_name]);
		 ugaq.push(['stats._trackEvent', config.vd_category+' Complete', items_meta.file, window.location.href]);
		is_complete = true;
	}
	
	function playing(){
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;	
		if(!vd_name) vd_name = config.vd_name;	
/* 		$(window).bind('beforeunload', function() {		
			if(!is_complete) ugaq.push(['stats._trackEvent', 'Video', 'Leave - '+vd_name , config.vd_name]);
		}); */ 
	}
	
    function p_p()
	{
		global_jw_var['load_ads1'] = true;
		setTimeout(function(){player.pause();},200);
		setTimeout(function(){player.play();},300);
	}
	
    player.onBeforePlay(setup);
    player.onPlay(playit);
	player.onAdComplete(p_p);
	player.onAdSkipped(p_p);
	player.onAdError(p_p);
	player.onPause(pauseit);
	player.onTime(playing);
	player.onComplete(completeit);	
	//player.onError(error_cb);	

    function resize() {
		var width = player.getWidth();
		var height = player.getHeight();
		if(is_ios) width = $(div).width();
		div.style.position = 'absolute';
        div.style.width = '278px';
        div.style.height = '80px';
        div.style.left = (width/2 - (278/2))+'px';
        div.style.top = (height/2 - 80)+'px';
		$(div).parent().css('position','relative');
		
    };

};
function jw_call_player(id,conf){
	var width = 600;
	var height = 538;
	var start = 0;
	if(conf.width) width = conf.width;
	if(conf.height) height = conf.height;
	if(conf.startparam) start = conf.startparam;
	var sconfig = {
		file : _get_file(conf.utoken),
		width: width,
		height: height,
		autostart: true,
		idlehide: true,
		primary: "flash",
		abouttext: 'About useetv.com',
		aboutlink: 'http://www.useetv.com/',
		startparam : start
	};
	if(conf.show_ads) sconfig.advertising = conf.show_ads;
	//if(conf.news_ticker) sconfig.news_ticker = conf.news_ticker;
	/* if(conf.news_ticker){
		var data_ticker = load_ticker(conf.news_ticker);
	} */
	
	
	var jw_obj = jwplayer(id).setup(sconfig);
	var container_div = document.createElement('div');
	$("#"+id).parent().append(container_div);				
	jw_register(jw_obj,conf,container_div); 				
}

function jw_call_player_mv(id, conf)
{
	var width = 800;
	var height = 522;
	var start = 0;
	if(conf.width) width = conf.width;
	if(conf.height) height = conf.height;
	if(conf.startparam) start = conf.startparam;
	var ifile = _get_file(conf.utoken);
	if(!conf.utoken) ifile = conf.utoken;
	var sconfig = {
		file : ifile,
		width: width,
		height: height,
		autostart: true,
		idlehide: true,
		primary: "flash",
		abouttext: 'About useetv.com',
		aboutlink: 'http://www.useetv.com/',
		startparam : start
	};
	if(conf.show_ads) sconfig.advertising = conf.show_ads;
	if(conf.news_ticker){
		$('head').append('<script src="/js/jquery.li-scroller.1.0.js" type="text/javascript" ></script>');
		$('head').append('<link href="/css/li-scroller.css" rel="stylesheet" type="text/css" />');
	}
	conf.auth_player = true;
	
	var jw_obj = jwplayer(id).setup(sconfig);
	if(conf.s!='' && conf.p=='0') jw_obj.load([{file:conf.s}]);
	var container_div = document.createElement('div');
	$("#"+id).parent().append(container_div);				
	jw_register_auth(jw_obj,conf,container_div);
}

function cekAuthPlayer(div_id, urls, dataInput, conf){
		if(global_jw_var['ajax_cek_play']) global_jw_var['ajax_cek_play'].abort();
		global_jw_var['ajax_cek_play'] = $.ajax({
			url: urls,
			type : 'post',
			data : dataInput,
			cache : false,
			dataType :'json',
			success: function(data) {
					conf.p 	 = data.resultCode;
					conf.m = data.resultMessage;
					conf.s = data.stream_url;
					if(typeof ga_track == 'function' && conf.p==0) ga_track('/stats/view/'+conf.vd_service+'/playing/'+dataInput.vod_id+'/'+conf.vd_name);
					jw_call_player_mv(div_id, conf);
				}
	});
}

var jw_register_auth = function(player, config, div) {
	var is_valid =false;
	var ugaq = config.gaq;
	var is_complete = false;
    function setup(evt) {
		resize();
        div.className = "alert alert-block";
		div.style.display = 'none'; 
		div.style.padding = '15px 10px'; 
		div.style.textAlign = 'center'; 
		//if ($.browser.webkit) div.style.backgroundColor = "#fff";
		if(global_jw_var['load_ads1'] && !global_jw_var['load_ads2']){
			global_jw_var['load_ads2'] = true;
			player.playAd(jingle_tag); 
		} 
		var alert_msg = '<fieldset>'+
		'<div>'+config.m+'</div>'+
		'<a href="'+config.back_url+'" class="btn btn-inverse" style="margin-top:20px;"> OK </a></fieldset>';
		if(player.getState()!="PLAYING" && config.p==0){
			player.play();
			is_valid = true;
		}else{
			div.style.display = '';
			div.innerHTML = alert_msg;
		}
		ugaq.push(['stats._setAccount', GA_STATS_ACCOUNT]);
         
    };
	
	function playit(){
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;
		if(!is_valid) player.stop();
		if(!vd_name) vd_name = config.vd_name;	
		 ugaq.push(['stats._trackEvent', config.vd_category+' Play', items_meta.file, window.location.href]);
	}
	
	function pauseit()
	{
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;
		if(!vd_name) vd_name = config.vd_name;			
		//ugaq.push(['stats._trackEvent', 'Video', 'Pause - '+vd_name, config.vd_name]);
	}
	
	function completeit()
	{
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;
		
		//ugaq.push(['stats._trackEvent', 'Video Complete', vd_name, config.vd_name]);
		ugaq.push(['stats._trackEvent', config.vd_category+' Complete', items_meta.file, window.location.href]);
		is_complete = true;
	}
	
	function playing(){
		var items_meta = player.getPlaylistItem();
		var vd_name = items_meta.title;
		if(!vd_name) vd_name = items_meta.description;	
		if(!vd_name) vd_name = config.vd_name;	 
	}
	
	function p_p()
	{
		global_jw_var['load_ads1'] = true;
		setTimeout(function(){player.pause();},200);
		setTimeout(function(){player.play();},300);
	}
	
    player.onBeforePlay(setup);
    player.onPlay(playit);
	player.onAdComplete(p_p);
	player.onAdSkipped(p_p);
	player.onAdError(p_p);
	player.onPause(pauseit);
	player.onTime(playing);
	player.onComplete(completeit);	
	
    function resize() {
		var width = player.getWidth();
		var height = player.getHeight();
		if(is_ios) width = $(div).width();
		div.style.position = 'absolute';
        div.style.width = '300px';
        div.style.height = '80px';
        div.style.left = (width/2 - (300/2))+'px';
        div.style.top = (height/2 - 80)+'px';
		$(div).parent().css('position','relative');
    };

};